import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/modle/more/entity/group_detail_entity.dart';
import 'package:shopping_group/modle/play/entity/after_pay_entity.dart';
import 'package:shopping_group/modle/play/ui/zfb_html_page.dart';
import 'package:shopping_group/utils/log_util.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class PingtuanPlayBloc implements BlocBase {
  //  Stream来初始化数量的操作
  StreamController<Object> _playCompleController = StreamController<Object>();
  //初始化动作
  StreamSink get playCompleteDate => _playCompleController.sink;

  StreamController<Object> _zfbPlayController = StreamController<Object>();
  StreamSink get zfbPlayDate => _zfbPlayController.sink;

  StreamController<Object> _validateController = StreamController<Object>();
  StreamSink get validateDate => _validateController.sink;

  PingtuanPlayBloc() {
    _playCompleController.stream.listen(playCompleData);
    _zfbPlayController.stream.listen(zfbPlayData);
    _validateController.stream.listen(validateData);
  }
  void validateData(data) {
    if (data is Map) {
      _validateTask(data);
    }
  }

  void playCompleData(data) {
    if (data is Map) {
      _playCompleteTask(data);
    }
  }

  void zfbPlayData(data) {
    if (data is Map) {
      _zfbPlayTask(data);
    }
  }

  void _validateTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        LogUtil.e(data.toString(),
            tag: '拼团验证入参.................//////////////');
        HttpUtilAll.post(Apis.PT_ISSHOP_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SvEntity params = SvEntity.fromJson(result);
            if (BaseConstant.SUCESS == params.val) {
              eventBus.fire('PO_ZI_FU_BAO' == data['payOption']
                  ? ZfbPingtuanStartEvent(params.joinId, '订单：${params.joinId}',
                      data['payVal'], params.joinId)
                  : ValidatePingtuanEvent(params.joinId));
            }
          }
          LogUtil.e(result.toString(),
              tag: '拼团验证结果.................//////////////');
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _zfbPlayTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());

    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        // LogUtil.e(data.toString(),
        //     tag: '支付宝拼团入参.................//////////////');
        HttpUtilAll.post(Apis.TESTZFB_PLAY_URL, data: data, headers: {},
            success: (result) {
          if (null != result) {
            SvEntity svEntity = SvEntity.fromJson(result);
            String openType;
            switch (data['type']) {
              case BaseConstant.SHOP_TYPE:
                openType = 'ESOT_SHOP';
                break;
              case BaseConstant.PINGTUAN_TYPE:
                openType = 'ESOT_JOIN';
                break;
              case BaseConstant.XIANJINGJUAN_TYPE:
                openType = 'ESOT_MO';
                break;
              case BaseConstant.FUGOUJUAN_TYPE:
                openType = 'ESOT_RB';
                break;
              default:
            }
            GroupDetailEntity entity =
                (data['entity'] is GroupDetailEntity) ? data['entity'] : null;
            RouteUtil.goParameter(ZfbHtmlPage(
              htmlData: svEntity.val.split(',')[1],
              openType: openType,
              orderId: data['id'],
              entity: entity,
            ));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _playCompleteTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());

    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.PLAY_COMPLETE_GROUP_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            AfterPayEntity parm = AfterPayEntity.fromJson(result);
            LogUtil.e(parm.toJson(), tag: 'PLAY_GROUP_URL/////////////////');
            if ('PO_ZI_FU_BAO' == data['payOption']) {
              eventBus.fire(ZfbPingtuanCompeteEvent());
            } else {
              eventBus.fire(PlayPingtuanOkEvent());
            }
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _playCompleController?.close();
    _zfbPlayController?.close();
    _validateController?.close();
  }
}
